package com.imooc.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 用于检测channel的心跳
 * @author liansen
 * @create 07-20-16:27
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        //判断evt是否是IdleStateEvent(空闲事件状态, 包含读空闲/写空闲/读写空闲)
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if(event.state() == IdleState.READER_IDLE){
                System.out.println("进入读空闲");
            }else if(event.state() == IdleState.WRITER_IDLE){
                System.out.println("进入写空闲");
            }else if(event.state() == IdleState.ALL_IDLE){

                System.out.println("channel关闭之前, clients中channel的数量为: " + WSHandler.clients.size() );

                //如果进入读写空闲, 就关闭channel
                Channel channel = ctx.channel();
                //channel关闭，会触发wsHandler中的handler的生命周期-remove函数
                channel.close();

                System.out.println("channel关闭之后, clients中channel的数量为: " + WSHandler.clients.size() );
            }
        }
    }
}
